﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
//using Newtonsoft.Json.Linq;
using NFine.Application;
using NFine.Application.ProductManage;
using NFine.Application.SystemManage;
using NFine.Code;
using NFine.Domain.Entity.ProductManage;
using NFine.Domain.Entity.SystemManage;
//using Webdiyer.WebControls.Mvc;

namespace NFine.Web.Areas.ProductManage.Controllers
{
    public class ProductController : ControllerBase
    {
        private ProductApp productApp = new ProductApp();
        private ProductImageApp imageApp = new ProductImageApp();
        //private CategoryApp categoryApp = new CategoryApp();
        //private ProductTypeApp typeApp = new ProductTypeApp();
        //private BrandApp brandApp = new BrandApp();
        //private AttributeApp attApp = new AttributeApp();
        //private ProductCategoryApp cateApp = new ProductCategoryApp();
        //private ProductAttributeApp pattrApp = new ProductAttributeApp();
        //private ProductSkuItemsApp productSkuItemsApp = new ProductSkuItemsApp();
        private string moduleName = "商品管理";

        [HttpGet]
        [HandlerAuthorize]
        public override ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetGridJson(Pagination pagination, string keyword)
        {
            var data = new
            {
                rows = productApp.GetList(pagination, keyword, true),
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }


        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetProductsGridJson()
        {
            Pagination pagination = new Pagination();
            pagination.page = 1;
            pagination.rows = 30;
            pagination.sord = "desc";
            pagination.sidx = "F_CreatorTime";
            var list = productApp.GetList(pagination);
            
            return Content(list.ToJson());
        }
        /// <summary>
        /// 获取单个商品
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(string keyValue)
        {
            //获取商品信息
            var data = productApp.GetForm(keyValue);
            data.Old_Image = data.F_ImageUrl;//旧图片
            data.productStock = data.F_Stock.IsEmpty() ? 0 : data.F_Stock.Value;


            //获取商品图片信息
            data.NotMapped_ImagesUrl = imageApp.GetListByParentId(keyValue);

            ////获取商品分类信息
            //ProductCategoryEntity Catelist = cateApp.GetListByProductID(keyValue);
            //if (Catelist != null)
            //    data.NotMapped_cate = Catelist.F_CategoryPath;

            ////获取商品属性值
            //data.attrList = pattrApp.GetListByParentId(keyValue);

            ////根据商品id获取规格信息数量
            //data.SkuItemCount = productSkuItemsApp.IsExitByProductId(keyValue);

            return Content(data.ToJson());
        }
        /// <summary>
        /// 保存商品信息
        /// </summary>
        /// <param name="pEntity"></param>
        /// <param name="keyValue">商品id</param>
        /// <param name="imageType"></param>
        /// <param name="jsonData">商品属性信息</param>
        /// <param name="selectedSku">商品规格信息</param>
        /// <param name="oldImages">商品旧图片</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [ValidateInput(false)]
        public ActionResult SubmitForm(ProductEntity pEntity, string keyValue, string imageType, string oldImages)
        {
            try
            {
                //商品属性信息
                JavaScriptSerializer serializer = new JavaScriptSerializer();

                //json 反序列化 修改之前的图片
                List<string> oldImagesList = null;
                if (!string.IsNullOrEmpty(oldImages))
                    oldImagesList = serializer.Deserialize<List<string>>(oldImages);

                pEntity.F_Stock = pEntity.productStock;
                pEntity.F_SaleStatus = 1;

                //保存商品主图
                string newPath = Request.MapPath("~/UploadFiles/" + imageType + "/");
                FileInfo file = null;

                if (!Directory.Exists(newPath))
                {
                    Directory.CreateDirectory(newPath);
                }
                var curUser = OperatorProvider.Provider.GetCurrent();
                if (!string.IsNullOrEmpty(keyValue))//修改
                {
                    if (string.IsNullOrEmpty(pEntity.F_ImageUrl) || pEntity.F_ImageUrl.Equals("&nbsp;"))
                    {
                        if (!string.IsNullOrEmpty(pEntity.Old_Image) && !pEntity.Old_Image.Equals("&nbsp;"))
                        {  //删除主图
                            file = new FileInfo(Request.MapPath("~" + pEntity.Old_Image));
                            if (file.Exists)
                                file.Delete();
                        }
                    }
                    else
                    {
                        if (pEntity.F_ImageUrl != pEntity.Old_Image)//重新上传过图片
                        {
                            file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + pEntity.F_ImageUrl));

                            if (!string.IsNullOrEmpty(pEntity.Old_Image) && !pEntity.Old_Image.Equals("&nbsp;"))
                            {
                                //删除旧图片
                                if (System.IO.File.Exists(Request.MapPath("~" + pEntity.Old_Image)))
                                {
                                    System.IO.File.Delete(Request.MapPath("~" + pEntity.Old_Image));
                                }
                            }
                            file.MoveTo(newPath + pEntity.F_ImageUrl);
                            pEntity.F_ImageUrl = "/UploadFiles/" + imageType + "/" + pEntity.F_ImageUrl;
                        }
                    }
                }
                else //添加
                {  //商家id  当前登录商家(当前登录为管理员，则商家为”0“)
                    pEntity.F_Supplier = "0";// curUser.UserType == 0 ? "0" : curUser.UserId;
                    pEntity.F_VisitCounts = 0;
                    pEntity.F_SaleCounts = 0;
                    if (!string.IsNullOrEmpty(pEntity.F_ImageUrl) && !pEntity.F_ImageUrl.Equals("&nbsp;"))
                    {
                        file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + pEntity.F_ImageUrl));

                        file.MoveTo(newPath + pEntity.F_ImageUrl);
                        pEntity.F_ImageUrl = "/UploadFiles/" + imageType + "/" + pEntity.F_ImageUrl;
                    }
                }
                //保存商品其他图片
                pEntity.NotMapped_Images = Common.DelLastComma(pEntity.NotMapped_Images);
                var otherImages = pEntity.NotMapped_Images.Split(',');

                if (!string.IsNullOrEmpty(keyValue) && oldImagesList != null && oldImagesList.Count > 0)//修改
                {

                    for (int j = 0; j < otherImages.Length; j++)
                    {
                        if (j >= oldImagesList.Count)//直接添加
                        {
                            if (!string.IsNullOrEmpty(otherImages[j]) && !otherImages[j].Equals("&nbsp;"))
                            {
                                file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + otherImages[j]));
                                file.MoveTo(newPath + otherImages[j]);
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(otherImages[j]) || otherImages[j].Equals("&nbsp;"))
                            {
                                if (!string.IsNullOrEmpty(oldImagesList[j]) && !oldImagesList[j].Equals("&nbsp;"))
                                {  //删除该图
                                    file = new FileInfo(Request.MapPath("~" + oldImagesList[j]));
                                    if (file.Exists)
                                        file.Delete();
                                }
                            }
                            else
                            {
                                if (otherImages[j] != oldImagesList[j])//重新上传过图片
                                {
                                    file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + otherImages[j]));

                                    if (!string.IsNullOrEmpty(oldImagesList[j]) && !oldImagesList[j].Equals("&nbsp;"))
                                    {
                                        //删除旧图片
                                        if (System.IO.File.Exists(Request.MapPath("~" + oldImagesList[j])))
                                        {
                                            System.IO.File.Delete(Request.MapPath("~" + oldImagesList[j]));
                                        }

                                        //   file.Replace(Request.MapPath("~/" + oldImagesList[j]), Request.MapPath("~/UploadFiles/temp/" + otherImages[j]));
                                        //  pEntity.NotMapped_Images = pEntity.NotMapped_Images.Replace(otherImages[j], oldImagesList[j]);
                                    }
                                    file.MoveTo(newPath + otherImages[j]);
                                }
                            }
                        }
                    }
                }
                else//添加
                {
                    if (!string.IsNullOrEmpty(pEntity.NotMapped_Images) && !pEntity.NotMapped_Images.Equals("&nbsp;"))
                    {
                        foreach (var s in otherImages)
                        {
                            // if (!s.StartsWith("/UploadFiles/Product"))//重新上传过图片
                            if (!string.IsNullOrEmpty(s) && !s.Equals("&nbsp;"))
                            {
                                file = new FileInfo(Request.MapPath("~/UploadFiles/temp/" + s));
                                if (file.Exists)
                                    file.MoveTo(newPath + s);
                            }
                        }
                    }
                }
                if (!string.IsNullOrEmpty(pEntity.F_ShopCategory) && !pEntity.F_ShopCategory.Equals("&nbsp;"))
                {
                    pEntity.F_ShopCategoryPath = pEntity.F_ShopCategory.Substring(pEntity.F_ShopCategory.Length - 36);
                }
                int result = productApp.SubmitForm(pEntity, keyValue, "/UploadFiles/" + imageType + "/");
                bool flag = result > 0 ? true : false;

                if (string.IsNullOrEmpty(keyValue))
                    addLog(moduleName, DbLogType.Create.ToString(), flag, flag ? "新增商品成功" : "新增商品失败");
                else
                    addLog(moduleName, DbLogType.Update.ToString(), flag, flag ? "修改商品成功" : "修改商品失败");
                if (flag)
                    return Success("操作成功。");
                else
                    return Error("操作失败。");
            }
            catch (Exception ex)
            {
                if (string.IsNullOrEmpty(keyValue))
                    addLog(moduleName, DbLogType.Create.ToString(), false, "新增商品失败，" + ex.Message);
                else
                    addLog(moduleName, DbLogType.Update.ToString(), false, "修改商品失败，" + ex.Message);
                return Error("操作失败：" + ex);
            }
        }


        /*  /// <summary>
          /// 获取商品类型 
          /// </summary>
          /// <returns></returns>
          [HttpGet]
          [HandlerAjaxOnly]
          public ActionResult GetTypeJson()
          {
              var data = typeApp.GetListByEnable();
              return Content(data.ToJson());
          }
          /// <summary>
          /// 根据商品类型获取品牌 
          /// </summary>
          /// <param name="pID">类型id</param>
          /// <returns></returns>
          [HttpGet]
          [HandlerAjaxOnly]
          public ActionResult GetBrandJson(string pID)
          {
              List<object> list = new List<object>();

              list.Add(new { id = "", text = "==请选择==" });

              var data = brandApp.GetListByType(pID);
              foreach (BrandEntity item in data)
              {
                  list.Add(new { id = item.F_Id, text = item.F_BrandName });
              }

              return Content(list.ToJson());
          }
          /// <summary>
          /// 获取商品属性
          /// </summary>
          /// <param name="typeID">商品类型id</param>
          /// <returns></returns>
          [HttpPost]
          [HandlerAjaxOnly]
          public JsonResult GetAttribute(string typeID, int usage)
          {
              List<AttributeEntity> list = new List<AttributeEntity>();
              if (!string.IsNullOrEmpty(typeID))
                  list = attApp.GetListByTypeId(typeID, usage);
              return Json(list, JsonRequestBehavior.AllowGet);
          }
          /// <summary>
          /// 获取分类数据  树形
          /// </summary>
          /// <param name="keyword"></param>
          /// <returns></returns>
          public JsonResult GetCombotreeJson(int flag)
          {
              List<TreeData> data = categoryApp.GetTreeList(flag);
              return Json(data, JsonRequestBehavior.AllowGet);
          }*/


        /// <summary>
        /// 查看商品详情
        /// </summary>
        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormInfo(string keyValue)
        {
            //获取商品基本信息
            var data = productApp.GetFormForView(keyValue);

            //获取商品图片信息
            data.NotMapped_ImagesUrl = imageApp.GetListByParentId(keyValue);
            ////获取商家名称
            //data.F_Supplier = supplierApp.getNameByUserID(data.F_Supplier);

            ////获取商品分类信息
            //data.CategoryNames = categoryApp.GetCategoryByIds(keyValue);

            ////根据商品id获取规格信息数量
            //data.SkuItemCount = productSkuItemsApp.IsExitByProductId(keyValue);

            return Content(data.ToJson());
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="keyValues">商品id ，分割</param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteForm(string keyValues)
        {
            try
            {
                //删除商品的图片
                string[] images = productApp.GetImagesByProductID(keyValues);

                int result = productApp.DeleteProducts(keyValues);
                if (result > 0)
                {
                    foreach (var i in images)
                    {
                        if (!string.IsNullOrEmpty(i) && System.IO.File.Exists(Request.MapPath("~" + i)))
                        {
                            //删除图片
                            System.IO.File.Delete(Request.MapPath("~" + i));
                        }
                    }

                    addLog(moduleName, DbLogType.Delete.ToString(), true, "删除商品成功");
                    return Success("删除成功。");
                }
                else
                {
                    addLog(moduleName, DbLogType.Delete.ToString(), false, "删除商品失败");
                    return Error("删除失败。");
                }
            }
            catch (Exception ex)
            {
                addLog(moduleName, DbLogType.Delete.ToString(), false, "删除商品失败，" + ex.Message);
                return Error("删除失败：" + ex);
            }
        }
        /// <summary>
        /// 商品上架/下架
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult InStock(string keyValue, int flag)
        {
            string info = flag == 0 ? "商品下架" : "商品上架";
            try
            {
                int result = productApp.inStock(keyValue, flag);
                if (result > 0)
                {
                    addLog(moduleName, DbLogType.Other.ToString(), true, info + "成功");
                    return Success(info + "成功。");
                }
                else
                {
                    addLog(moduleName, DbLogType.Other.ToString(), false, info + "失败");
                    return Error(info + "失败。");
                }
            }
            catch (Exception ex)
            {
                addLog(moduleName, DbLogType.Other.ToString(), false, info + "失败，" + ex.Message);
                return Error(info + "失败：" + ex);
            }
        }
        /// <summary>
        /// 商品审核
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        [HttpPost]
        [HandlerAjaxOnly]
        [HandlerAuthorize]
        [ValidateAntiForgeryToken]
        public ActionResult auditProduct(string keyValue)
        {
            try
            {
                int result = productApp.auditProducts(keyValue);
                if (result > 0)
                {
                    addLog(moduleName, DbLogType.Other.ToString(), true, "商品审核成功");
                    return Success("商品审核成功。");
                }
                else
                {
                    addLog(moduleName, DbLogType.Other.ToString(), false, "商品审核失败");
                    return Error("商品审核失败。");
                }
            }
            catch (Exception ex)
            {
                addLog(moduleName, DbLogType.Other.ToString(), false, "商品审核失败，" + ex.Message);
                return Error("商品审核失败：" + ex);
            }
        }


        public ActionResult EditorUpload(HttpPostedFileBase fileDataFileName)
        {
            string newFilePath = "";
            string msg = "";
            if (fileDataFileName != null)
            {
                //处理乱码
                ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.Charset = "UTF-8";
                string uploadPath = Request.MapPath("~/UploadFiles/editor/");
                // 文件上传后的临时保存路径
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string fileName = Path.GetFileName(fileDataFileName.FileName); //原始文件名称
                string fileExtension = Path.GetExtension(fileName); //文件扩展名
                string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension; //保存文件名称
                newFilePath = uploadPath + saveName;
                fileDataFileName.SaveAs(newFilePath);
                msg = "{\"success\":\"" + true + "\",\"file_path\":\"/UploadFiles/editor/" + saveName + "\"}";
            }
            return Content(msg);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Upload(HttpPostedFileBase fileData)
        {
            string newFilePath = "";
            if (fileData != null)
            {
                //处理乱码
                ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                ControllerContext.HttpContext.Response.Charset = "UTF-8";
                // 文件上传后的临时保存路径
                if (!Directory.Exists(Request.MapPath("~/UploadFiles/temp/")))
                {
                    Directory.CreateDirectory(Request.MapPath("~/UploadFiles/temp/"));
                }
                string uploadPath = Request.MapPath("~/UploadFiles/temp/");
                string fileName = Path.GetFileName(fileData.FileName);      //原始文件名称
                string fileExtension = Path.GetExtension(fileName);         //文件扩展名
                string saveName = DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension; //保存文件名称
                newFilePath = uploadPath + saveName;
                fileData.SaveAs(newFilePath);
                ControllerContext.HttpContext.Response.Write(saveName);
            }
            return Success("上传成功");
        }
        [HttpGet]
        public ActionResult Show(int pageId = 1)
        {
            Pagination pagination = new Pagination();
            pagination.page = pageId;
            pagination.rows = 30;
            pagination.sord = "desc";
            pagination.sidx = "F_CreatorTime";
            var list = productApp.GetList(pagination);
            //PagedList<ProductEntity> proList = list.ToPagedList(pageId, pagination.rows);
            //proList.TotalItemCount = pagination.records;
            //proList.CurrentPageIndex = pageId;
            return View(list);
        }
        public ActionResult ProductInfo(string id)
        {
            var data = productApp.GetForm(id);
            //获取商品图片信息
            data.NotMapped_ImagesUrl = imageApp.GetListByParentId(id);
            return View(data);
        }
    }
}
